#! /usr/bin/env python3
import os
import sys
import json
import cgi
sys.path.append(os.path.dirname(os.getcwd()))
from searchModule import searchMessage
from webPathUtil import fromPathToHtml

_PLATFORM = "win" in sys.platform and "windows" or "linux"


def get_config(path="config.json"):
    with open(path, "r+", encoding="utf-8") as f:
        json_dict = json.load(f)
        return json_dict


def get_rec_dict(dict_ins, result_list=list()):
    for key in dict_ins:
        if ".md" in key:
            result_list.append(key)
        value = dict_ins[key]
        if isinstance(value, dict):
            result_list = get_rec_dict(dict_ins=value, result_list=result_list)
    return result_list


def get_main_html(body):
    head = "Content-type:text/html\n\n"
    with open("html/main.web", "r", encoding="UTF-8") as f:
        constent = f.read()
        constent = constent.format(main=body, sel_part="")
        return head + constent


def get_search_html(select, cont):
    with open("html/search.web", "r", encoding="UTF-8") as f:
        constent = f.read()
        constent = constent.format(body=cont, select=select)
        return constent


def main(note_path, except_list, execf, st=0):
    last_conts = ""
    form = cgi.FieldStorage()
    text = form.getvalue("keyword")
    types = form.getvalue("typse")
    if text is None:
        text = ''
    if types is None:
        types = 1

    note_list = os.listdir(note_path)
    select_str = ""
    note_list.insert(0, 'ALL')
    i = 0
    for n in note_list:
        if ".git" not in n:
            select_str += "    <option value=" + str(i) + ">" + str(n) + "</option>\n"
            i += 1
    last = list()
    result = fromPathToHtml.file_tree(note_path, except_list)
    last = get_rec_dict(result, last)

    md_list = list()
    if int(types) == 0:
        current_path = note_path
        md_list = last
    else:
        current_path = os.path.join(note_path, note_list[int(types)])
        last = list()
        result = fromPathToHtml.file_tree(current_path, except_list)
        last = get_rec_dict(result, last)
        md_list = last

    if st == 1:
        for path in md_list:
            true_path = os.path.join(current_path, path)
            rst = searchMessage.main(true_path, text, "markdownWeb.py", note_path)
            last_conts += str(rst)
    html = get_main_html(get_search_html(select=select_str, cont=last_conts))
    print(html)


if __name__ == "__main__":
    config = get_config()
    note_path = config.get("note_path", {}).get(_PLATFORM, None)
    except_list = config.get("except_list", None)
    main(note_path, except_list, execf="searchWeb.py", st=1)
